package try_with_resource;

import javax.swing.plaf.nimbus.State;
import java.sql.*;

public class JDBCDemo {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {

        String url = "jdbc:mysql://127.0.0.1:3306/testbase?useSSL=false&characterEncoding=utf8";
        String user = "root";
        String password = "missh111";

        //方法一
        Class.forName("com.mysql.jdbc.Driver");
        {
            //不使用try-with-resource的写法
            Connection connection = null;
            try {
                connection = DriverManager.getConnection(url, user, password);
                //执行具体的操作
                try (Statement statement = connection.createStatement()) {
                    String sql = "select * from exam_result";
                    try (ResultSet resultSet = statement.executeQuery(sql)) {
                        while (resultSet.next()) {
                            System.out.println(resultSet.getString(1));
                        }
                    }
                }
            } finally {
                if (connection != null) {//只要连接成功了，就应该调用close关闭连接
                    connection.close();
                }
            }

        }

        //使用try-with-resource的写法，1.8之后支持，目的就是简化代码
        {
            try (Connection connection = DriverManager.getConnection(url, user, password)) {
                //执行具体的操作
                try (Statement statement = connection.createStatement()) {
                    String sql = "show tables";
                    try (ResultSet resultSet = statement.executeQuery(sql)) {
                        while (resultSet.next()) {
                            System.out.println(resultSet.getString(1));
                        }
                    }
                }
            }
        }       //会自动调用connection.close(),编译器会自动帮你加上相应的代码
    }
}
